<template>
    <div id="departments">
        <!-- 面包导航 -->
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{this.$router.currentRoute.name }}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 右侧卡片区域 -->
        <!-- 缴费项目列表卡片区 -->
        <el-card class="box-card">
            <!--   gutter是指栅格间间隔，offset是指栅格左侧的间隔格数         -->
            <el-row :gutter="20">
                <el-col :span="8"><!-- 栅格占据的8列数 -->
                    <el-input
                            size="small"
                            clearable
                            v-model="queryMap.pmtypename"
                            placeholder="请输入缴费项目名称查询"
                            @clear="search"
                            class="input-with-select"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="2">
                    <el-button
                            size="small"
                            v-hasPermission="'department:add'"
                            type="success"
                            icon="el-icon-circle-plus-outline"
                            @click="toAdd"
                    >添加</el-button>
                </el-col>
                <!--                <el-col :span="2">-->
                <!--                    <el-button-->
                <!--                            size="small"-->
                <!--                            icon="el-icon-download"-->
                <!--                            v-hasPermission="'department:export'"-->
                <!--                            @click="downExcel"-->
                <!--                    >导出</el-button>-->
                <!--                </el-col>-->
            </el-row>
            <!-- 表格区域 -->
            <template>
                <el-table
                        border
                        size="small"
                        v-loading="loading"
                        stripe
                        :data="departmentData"
                        style="width: 100%;margin-top:20px;"
                        height="460"
                >
                    <el-table-column prop="pmtypeid" type="index" label="ID" width="50"></el-table-column>
                    <el-table-column label="缴费项目名称" width="200">
                        <template slot-scope="scope">
                            <i :class="scope.row.icon" style="font-size: 15px; margin-right: 10px;"></i>
                            <span style="text-align: center">{{ scope.row.pmtypename }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" width="200">
                        <template slot-scope="scope">
                            <i class="el-icon-time"></i>
                            <span style="margin-left: 10px">{{ scope.row.createtime }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="status" label="状态" width="100">
                        <template slot-scope="scope">
                            <el-tag size="mini" type="danger" effect="plain" v-if="scope.row.status==0">启用</el-tag>
                            <el-tag size="mini" effect="plain" v-if="scope.row.status==1">禁用</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注">
                        <template slot-scope="scope">
                            <!-- 光标放在文字上面 悬出内容区域 -->
                            <el-popover trigger="hover" placement="top">
                                <p>备注: {{ scope.row.remakes }}</p>
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">{{ scope.row.remakes }}</el-tag>
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    v-hasPermission="'department:edit'"
                                    type="text"
                                    size="small"
                                    icon="el-icon-edit"
                                    @click="edit(scope.row)"
                            >编辑</el-button>

                            <el-button
                                    v-hasPermission="'department:delete'"
                                    type="text"
                                    size="small"
                                    icon="el-icon-delete"
                                    @click="del(scope.row.deptId)"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <!-- 分页 -->
            <el-pagination
                    style="margin-top:10px;"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="this.queryMap.pageNum"
                    :page-sizes="[7, 10, 15, 20]"
                    :page-size="this.queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>
            <!-- 缴费项目别添加弹出框 -->
            <el-dialog :title="title" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog">
        <span>
          <el-form
                  :model="addPayType"
                  :rules="addRules"
                  ref="addPayTypeRef"
                  label-width="100px"
                  class="demo-ruleForm"
          >

            <el-form-item label="缴费项目名称" >
              <el-input type="text" v-model="addPayType.pmtypename"></el-input>
            </el-form-item>
               <el-form-item label="图标" >
              <el-input type="text" v-model="addPayType.icon"></el-input>
            </el-form-item>
           <el-form-item label="创建时间">
              <el-date-picker
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                      v-model="addPayType.createtime"
                      style="width: 100%"
              ></el-date-picker>
            </el-form-item>
             <el-form-item label="状态">
                <el-select
                        clearable
                        v-model="addPayType.status"
                        placeholder="请选择状态"
                >
                    <el-option label="启用" :value="0"></el-option>
                    <el-option label="禁用" :value="1"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="备注">
              <el-input type="textarea" v-model="addPayType.remakes"></el-input>
            </el-form-item>
          </el-form>
        </span>
                <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add" :disabled="btnDisabled" :loading="btnLoading">确 定</el-button>
        </span>
            </el-dialog>


        </el-card>
    </div>
</template>

<script>
    import axios from "axios";
    export default {
        data() {
            const checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[34578]\d{9}$$/;
                if (!value) {
                    return callback(new Error("电话号码不能为空"));
                }
                if (!Number.isInteger(+value)) {
                    return callback(new Error("请输入数字值"));
                } else {
                    if (phoneReg.test(value)) {
                        return  callback();
                    } else {
                        return callback(new Error("电话号码格式不正确"));
                    }
                }
            };
            return {
                title:'添加缴费项目',
                btnLoading: false,
                btnDisabled: false,
                loading: true,
                editDialogVisible: false,
                addDialogVisible: false, //添加弹框是否显示
                total: 0, //总共多少条数据
                departmentData: [], //表格数据
                queryMap: { pageNum: 1, pageSize: 7 }, //查询对象
                addPayType: {pmtypename:''}, //添加表单数据
                editRuleForm: {}, //修改表单数据
                addRules: {
                }, //添加验证
                getname:'',
                shcoolClass:[],
                queryStudList:[],
            };
        },
        methods: {
            querySearch(queryString, cb) {
                if(queryString!='') {//输入框中有值
                    this.findStuList(queryString, (data) => {
                        console.log(data);
                        var results = queryString ? data.filter(this.createStateFilter(queryString)) : data;
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(() => {
                            cb(results);
                        }, 5000*Math.random());
                    })
                }
            },
            findStuList(query,fun){
                if(query!='' && query !=null && query!= undefined){
                    let params = {
                        studentName:query
                    }
                    this.$http.post('/class/findStuList',params).then((res) =>{
                        this.queryStudList = res.data
                        this.shcoolClass = []
                        if(this.queryStudList.length>0){
                            this.queryStudList.forEach((item)=>{
                                this.shcoolClass.push({
                                    value:item.studentId,
                                    name:item.studentName
                                })
                            })
                        }else{
                            this.shcoolClass.push({
                                value:"未找到相关结果",
                                name:"未找到相关结果",
                            })
                        }
                        fun(this.shcoolClass);
                    })
                }

            },
            handleSelect(selected) {
                this.addPayType.studentname = selected.name
                this.addPayType.studentid = selected.value+''
            },
            createStateFilter(queryString) {
                return (item) => {
                    //item字段是全部所匹配到的大小写汉子
                    return (
                        item.name.toLowerCase().indexOf(queryString.toLowerCase())>-1
                    )
                }
            },
            toAdd(){
                this.addDialogVisible = true
            },
            getName(id){
                let empName = '';
                this.$http.get('/class/getEmpNameById/'+id).then((res) =>{
                    this.getname = res.data.data
                })
                console.log(this.getname)
                return this.getname;
            },
            /**
             * 加载缴费项目表格
             */
            downExcel() {
                const $this = this;
                const res = axios
                    .request({
                        url: "http://localhost:8989/system/department/excel",
                        method: "post",
                        responseType: "blob"
                    })
                    .then(res => {
                        if (res.headers["content-type"] === "application/json") {
                            return $this.$message.error(
                                "Subject does not have permission [department:export]"
                            );
                        }
                        const data = res.data;
                        let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
                        var a = document.createElement("a");
                        document.body.appendChild(a);
                        a.href = url;
                        a.download = "缴费项目列表.xls";
                        a.click();
                        window.URL.revokeObjectURL(url);
                    });
            },
            /**
             * 搜索缴费项目
             */
            search() {
                this.queryMap.pageNum = 1;
                this.getDepartmentList();
            },
            /**
             * 删除缴费项目
             */
            async del(id) {
                let falg = await this.$confirm(
                    "此操作将永久删除该缴费项目, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
                if ("confirm" === falg) {
                    const {data: res} = await this.$http.delete(
                        "/payTpye/delete/" + id
                    );
                    if (res.success) {
                        this.$message.success("缴费项目删除成功");
                        await this.getDepartmentList();
                    } else {
                        this.$message.error(res.data.errorMsg);
                    }
                }
            },
            /**
             * 更新缴费项目
             */
            update: async function (){
                (this.btnLoading = true), (this.btnDisabled = true);
                const {data: res} = await this.$http.post(
                    "/payTpye/update",
                    this.addPayType
                );
                if (res.success) {
                    this.$message.success("缴费项目修改成功");
                    this.addPayType = {};
                    await this.getDepartmentList();
                } else {
                    return this.$message.error("缴费项目修改失败:" + res.data.errorMsg);
                }
                this.addDialogVisible = false;
                (this.btnLoading = false), (this.btnDisabled = false);
            },
            /**
             * 编辑获取缴费项目信息
             * @param {Object} id
             */
            edit(row) {
                this.title ='编辑缴费项目'
                this.addDialogVisible = true;
                this.addPayType = row
                //this.addPayType.obtainempid = row.obtainempid
            },
            //添加
            add: function () {
                this.$refs.addPayTypeRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        if(this.addPayType.pmtypeid){
                            this.update()
                        }else{
                            this.saveAdultexam()
                        }

                    }
                });
            },
            saveAdultexam: async function () {
                (this.btnLoading = true), (this.btnDisabled = true);
                const {data: res} = await this.$http.post(
                    "/payTpye/add",
                    this.addPayType
                );
                if (res.success) {
                    this.$message.success("缴费项目添加成功");
                    this.addPayType = {};
                    await this.getDepartmentList();
                } else {
                    return this.$message.error("缴费项目添加失败:" + res.data.errorMsg);
                }
                this.addDialogVisible = false;
                (this.btnLoading = false), (this.btnDisabled = false);
            },
            //加载缴费项目别列表
            async getDepartmentList() {
                const { data: res } = await this.$http.get(
                    "/payTpye/findPayMentTypeList",
                    {
                        params: this.queryMap
                    }
                );
                if (!res.success) {
                    return this.$message.error("获取缴费项目列表失败:"+res.data.errorMsg);
                } else {
                    this.total = res.data.total;
                    this.departmentData = res.data.rows;
                }
                this.loading = false;
            },
            //改变页码
            handleSizeChange(newSize) {
                this.queryMap.pageSize = newSize;
                this.getDepartmentList();
            },
            //翻页
            handleCurrentChange(current) {
                this.queryMap.pageNum = current;
                this.getDepartmentList();
            },
            //关闭弹出框
            closeAddDialog() {
                this.$refs.addPayTypeRef.clearValidate();
                this.addPayType = {};
            },
            //关闭弹出框
            closeEditDialog() {
                this.$refs.editRuleFormRef.clearValidate();
                this.editRuleForm = {};
            }
        },
        created() {
            this.getDepartmentList();
            // setTimeout(() => {
            //     this.loading = false;
            // }, 500);
        }
    };
</script>
